package cn.fengwoo.springBoot.service.impl;


import cn.fengwoo.springBoot.entity.Token;
import cn.fengwoo.springBoot.enums.ResultEnum;
import cn.fengwoo.springBoot.exception.FengwooException;
import cn.fengwoo.springBoot.repository.TokenRepository;
import cn.fengwoo.springBoot.service.TokenService;
import cn.fengwoo.springBoot.utils.frequent.ContextHolderUtils;
import cn.fengwoo.springBoot.utils.frequent.Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.net.UnknownHostException;
import java.util.Date;
import java.util.List;

/**
 * Created by fangdaji on 2018/1/10.
 */
@Service
@Transactional
public class TokenServiceImpl implements TokenService {

    @Autowired
    private TokenRepository repository;

    /**
     * 口令生成与保存
     *
     * @param userId
     * @return
     */
    public String generateToken(Integer userId,String phone) throws UnknownHostException {
        HttpServletRequest request = ContextHolderUtils.getRequest();

        String token = Util.getToken(phone, Util.getIpAddr(request));
        // 口令生成与保存
        Token kToken = new Token();
        kToken.setAccessToken(token);
        kToken.setUserId(userId);
        kToken.setExpires(new Date(new Date().getTime() + (long) 30 * 24 * 60 * 60 * 1000));
        kToken.setLastSigninIp(Util.getIp2(request));
        kToken.setLastSigninTime(new Date());

        updateToken(kToken);

        return token;
    }

    /**
     * 口令更新
     *
     * @param token
     * @return
     */
    private Token updateToken(Token token) {
        Token oldToken = null;
        try {

            List<Token> tokens = repository.findByUserId(token.getUserId());
            if(tokens!=null&&tokens.size()>0){
                oldToken = tokens.get(0);
            }

        } catch (Exception e) {
            List<Token> tokens = repository.findByUserId(token.getUserId());
            repository.delete(tokens);
        }

        try {
            if (oldToken != null) {
                token.setId(oldToken.getId());
                repository.save(token);
            } else {
                repository.save(token);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return token;
    }

    public Boolean checkAccessToken(String accessToken){

        if (accessToken == null) {
            throw new FengwooException(ResultEnum.NOT_TOKEN);
        }

        Token t = repository.findByAccessToken(accessToken);
        if (t == null) {
            throw new FengwooException(ResultEnum.OTHER_LOGIN);
        }else{
            // 有效日期
            Date expires = t.getExpires();
            if (expires.getTime() - System.currentTimeMillis() < 0) {
                throw new FengwooException(ResultEnum.TOKEN_FAILURE);
            }
            // 上次登录时间
            t.setLastSigninTime(new Date());

            // 有效期设置为30天;
            t.setExpires(new Date(new Date().getTime() + (long) 30 * 24 * 60 * 60 * 1000));
            repository.save(t);

            return true;
        }
    }


}
